<template>
  <div class="login">
    <el-form :ref="options.ref" :model="loginModel" :rules="options.rules" class="login-form">
      <h3 class="title">{{ options.title }}</h3>

      <el-form-item prop="username">
        <el-input v-model="loginModel.username" type="text" size="large" auto-complete="off" placeholder="请输入用户名">
          <template #prefix>
            <el-icon :size="20">
              <User />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input v-model="loginModel.password" type="password" size="large" auto-complete="off" placeholder="请输入密码">
          <template #prefix>
            <el-icon :size="20">
              <Lock />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click.prevent="handleLogin" class="submit-btn">
          <span v-if="!loading">登录</span>
          <span v-else>登录...</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name="Login">
import { ref, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { useAccountStore } from '@/store/account'
import { encrypt } from '@/utils/jsencrypt'
import _ from 'lodash'

import settings from '@/settings'

const options = {
  ref: 'loginRef',
  title: settings.title,
  action: undefined,
  rules: []
}

const loginModel = ref({
  username: 'admin',
  password: '123456'
})

const loading = ref(false)
const { proxy } = getCurrentInstance()
const router = useRouter()
const accountStore = useAccountStore()

function handleLogin() {
  proxy.$refs[options.ref].validate((valid) => {
    if (valid) {
      const data = _.cloneDeep(loginModel.value)
      // 密码加密
      data.password = encrypt(data.password)
      // 登录请求
      loading.value = true
      accountStore
        .Login(data)
        .then((res) => {
          router.push({ path: '/' })
          loading.value = false
        })
        .catch((e) => {
          console.log(e)
          loading.value = false
        })
    }
  })
}
</script>
<style scoped lang="scss">
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-image: url('@/assets/images/login-background.jpg');
  background-size: cover;

  .title {
    margin: 0 auto 30px auto;
    text-align: center;
  }

  .login-form {
    border-radius: 8px;
    background: #fff;
    width: 400px;
    padding: 25px 25px 5px 25px;

    .submit-btn {
      width: 100%;
    }
  }
}
</style>
